/*
   Copyright 2011-2012 gtalent2@gmail.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package world

import (
	"../models"
	eutil "../util"
	scriptPkg "../worldscript"
	"time"
)

type interpreter struct {
	running  bool
	zone     *Zone
	script   scriptPkg.Script
	deadChan chan interface{}
	sprites  map[string]Sprite
}

func new_interpreter(script scriptPkg.Script) *interpreter {
	var i interpreter
	i.deadChan = make(chan interface{})
	i.script = script
	return &i
}

//Blocks until execution of the script is complete.
func (me *interpreter) done() {
	<-me.deadChan
}

func (me *interpreter) stop() {
	me.running = false
	<-me.deadChan
	me.zone.scriptRemover <- me
}

//Runs the script.
//Takes a channel to let other threads know when execution is done.
func (me *interpreter) run() {
	me.running = true
	var loopStack []int
	for i := 0; i < len(me.script) && me.running; i++ {
		me.zone.world.pause.wait()
		v := me.script[i]
		switch v.OpCode {
		case 0: // load sprite
			{
				instr := v.Instruction.(scriptPkg.LoadSprite)
				var ls models.Sprite
				eutil.LoadObj(instr.Path, &ls)
				me.zone.loadSprite(ls, instr.X, instr.Y, instr.Layer)
			}
		case 1: // delete sprite
			{
				instr := v.Instruction.(scriptPkg.DeleteSprite)
				s := me.sprites[instr.Name]
				me.zone.deleteSprite(s)
			}
		case 2: // move sprite
			{
				instr := v.Instruction.(scriptPkg.MoveSprite)
				s := me.sprites[instr.Name].(*MovableSprite)
				for success := false; !success; {
					switch instr.Direction {
					case 0: //up
						success = s.MoveUp()
					case 1: //down
						success = s.MoveDown()
					case 2: //left
						success = s.MoveLeft()
					case 3: //right
						success = s.MoveRight()
					}
					time.Sleep(toNano(1000))
				}
			}
		case 3: // try move sprite
			{
				instr := v.Instruction.(scriptPkg.MoveSprite)
				s := me.sprites[instr.Name].(*MovableSprite)
				switch instr.Direction {
				case 0: //up
					s.MoveUp()
				case 1: //down
					s.MoveDown()
				case 2: //left
					s.MoveLeft()
				case 3: //right
					s.MoveRight()
				}
			}
		case 4: // start loop block
			loopStack = append(loopStack, i)
		case 5: // restart current loop
			i = loopStack[len(loopStack)-1]
			loopStack = loopStack[:len(loopStack)-1]
		case 6: // sleep
			{
				instr := v.Instruction.(scriptPkg.Sleep)
				time.Sleep(toNano(instr.Time))
			}
		}
	}
	close(me.deadChan)
}
